<script setup name="billconfig">
import {
  GetListAPI,
  DelDataAPI,
  AddDataAPI,
  EditDataAPI,
  GetMenuPermsAPI,
  GetMenuPermAPI
} from '@/api/system/billconfig'
import { GetListAPI as billListAPI } from '@/api/system/ofcode'
import BillConfigs from '@/components/XiaoheComponents/billConfigs/index.vue'
const tabs = ref('检验配置')
const { proxy } = getCurrentInstance()
const {
  sys_handover_method, //交接方式
  item_rank, // 送检阶别
  sys_inspection_type, // 检验类型
  sys_inspection_method, // 送检方式
  sys_control_items, // 管控项目
  sys_material_category, // 物料类别
  sys_ofcode_type
} = proxy.useDict(
  'sys_handover_method',
  'sys_ofcode_type',
  'item_rank',
  'sys_inspection_type',
  'sys_inspection_method',
  'sys_control_items',
  'sys_material_category'
)

// 表单ref
const FormsRef = ref(null)

// 选中ID
const Ids = ref([])

// 是否禁用修改按钮
const Single = ref(false)

// 是否禁用删除按钮
const DelDisabled = ref(false)

// 列表数据
const TableData = ref([{}, {}, {}])

// 列表总数量
const total = ref(0)

// 列表加载
const loading = ref(false)

// 保存按钮加载
const BtnLoading = ref(false)

// 信息展示状态
const Drawer = ref(false)

// 新增弹窗
const dialogVisible = ref(false)

// 单据选择弹窗
const BillIsShow = ref(false)

// 弹窗 标题
const title = ref('新增')

// 表格表单 数据
const TableForm = ref([])

// 勾选 表格表单
const formTebls = ref([])

const ruleFormRef = ref()

const docTheRulesOpt = ref([])

const anjianList = ref([])
// 查询条件
const query = reactive({
  pageNum: 1,
  pageSize: 10,
  ofCodeType: '',
  ofCodeStr: '',
  ofCodeName: '',
  selectTime: ''
})

/**
 * 查询枚举
 */
const SelectList = ref([
  { model: 'selectTime', type: '日期范围' },
  { label: '配置编码', model: 'docCode', type: '输入框', placeholder: '请输入配置编码' },
  { label: '配置名称', model: 'docName', type: '输入框', placeholder: '请输入配置名称' },
  { label: '配置单据', model: 'docConfig', type: '层级下拉', placeholder: '请输入配置单据名称' }
])

/**
 * 弹窗表单
 */
// 表单
const ruleForm = reactive({
  docCode: '', // 配置编码
  docName: '', // 配置名称
  docHandoverMethod: '', // 交换方式
  docConfig: '', // 配置单据
  docTheRules: '', // 编码规则
  docExcessMark: '2', // 超收标志 0为超收 1超收
  docHairMark: '2', // 超发标志 0为超收 1超收
  docInspectionMark: '2', // 送检标志
  docHandoverMark: '2', // 交接标志
  docConfigCode: {
    check: [],
    audit: [] //审核配置jso
  } // arr
})

// 表格表单校验
const rules = reactive({
  docCode: [
    { required: true, message: '请填写配置编码', trigger: 'blur' },
    { validator: proxy.noChinese, trigger: 'blur' }
  ],
  docName: [{ required: true, message: '请填写配置名称', trigger: 'blur' }],
  docConfig: [{ required: true, message: '请填写配置单据', trigger: 'blur' }],
  docTheRules: [{ required: true, message: '请选择编码规则', trigger: 'change' }]
})

// 勾选表格表单
const formTeblChange = row => {
  formTebls.value = row
}

// 码段添加
const addTypeFn = () => {
  if (tabs.value == '检验配置')
    ruleForm.docConfigCode.check.push({
      checkSubmit: null, // 送检阶别
      checkType: null, // 送检类型
      checkMode: null // 送检方式
    })
  if (tabs.value == '审核配置')
    ruleForm.docConfigCode.audit.push({
      auditControl: null, // 管控项目
      auditTrigger: null, // 触发按键
      auditMalType: null // 物料类别
    })
}

// 删除表格表单
const removeTypeFn = scope => {
  let arr = []
  if (tabs.value == '检验配置') arr = ruleForm.docConfigCode.check
  if (tabs.value == '审核配置') arr = ruleForm.docConfigCode.audit

  if (formTebls.value.length > 0) {
    formTebls.value.forEach(item => {
      const Find = arr.findIndex(itemy => item.docId == itemy.docId)
      arr.splice(Find, 1)
    })
  } else {
    arr.splice(arr.length - 1, 1)
  }
}

// 列表选中 及 判断是否禁用删除 || 修改
const handleSelectionChange = selection => {
  Ids.value = selection.map(item => item.docId)
  Single.value = selection.length != 1
  DelDisabled.value = !selection.length
}
handleSelectionChange([])

// 新增
const add = () => {
  getMenuPerm()
  dialogVisible.value = true
  title.value = '新增'
}

// 修改
const edit = async val => {
  try {
    proxy.$modal.loading('请稍候...')
    getMenuPerm()
    title.value = '修改'
    for (let Key in val) {
      ruleForm[Key] = val[Key]
    }

    ruleForm.docConfig = val.docConfig
    await getAnjian(val.docConfig)
    ruleForm.docHandoverMethod = String(val.docHandoverMethod == 0 ? '' : val.docHandoverMethod)

    ruleForm.docConfigCode.audit = val.documentAuditDtoList.map(item => ({
      auditControl: String(item.auditControl),
      auditMalType: String(item.auditMalType),
      auditTrigger: String(item.auditTrigger)
    }))
    ruleForm.docConfigCode.check = val.documentCheckDtoList.map(item => ({
      checkMode: String(item.checkMode),
      checkSubmit: String(item.checkSubmit),
      checkType: String(item.checkType)
    }))
    dialogVisible.value = true
  } catch {
  } finally {
    proxy.$modal.closeLoading()
  }
}

// 查看看
const look = async val => {
  try {
    proxy.$modal.loading('请稍候...')
    getMenuPerm()
    title.value = '查看'
    for (let Key in val) {
      ruleForm[Key] = val[Key]
    }
    ruleForm.docConfig = val.docConfig

    ruleForm.docHandoverMethod = String(val.docHandoverMethod == 0 ? '' : val.docHandoverMethod)
    await getAnjian(val.docConfig)
    ruleForm.docConfigCode.audit = val.documentAuditDtoList.map(item => ({
      auditControl: String(item.auditControl),
      auditMalType: String(item.auditMalType),
      auditTrigger: String(item.auditTrigger)
    }))
    ruleForm.docConfigCode.check = val.documentCheckDtoList.map(item => ({
      checkMode: String(item.checkMode),
      checkSubmit: String(item.checkSubmit),
      checkType: String(item.checkType)
    }))
    dialogVisible.value = true
  } catch {
  } finally {
    proxy.$modal.closeLoading()
  }
}

// 新增提交
const addSubmit = async () => {
  BtnLoading.value = true
  try {
    const valid = await ruleFormRef.value.validate()
    if (!valid) return
    const arr = ruleForm.docConfigCode

    // 送检配置开启时
    if (ruleForm.docInspectionMark == 1) {
      if (arr.check.length < 1) return proxy.warningMsg('至少添加一条检验配置')
      const checkIf = arr.check.some(item => item.checkSubmit && item.checkType && item.checkMode)
      if (!checkIf) return proxy.warningMsg('请填写一条完整的检验配置')
    }
    // if (arr.check.length < 1) return proxy.warningMsg('至少添加一条检验配置')
    // const checkIf = arr.check.some(item => item.checkSubmit && item.checkType && item.checkMode)
    // if (!checkIf) return proxy.warningMsg('请填写一条完整的检验配置')

    // if (arr.audit.length < 1) return proxy.warningMsg('至少添加一条审核配置')
    // const auditIf = arr.audit.some(item => item.auditControl && item.auditTrigger && item.auditMalType)
    // if (!auditIf) return proxy.warningMsg('请填写一条完整的审核配置')

    await AddDataAPI(ruleForm)
    proxy.successMsg('新增成功')
    close()
    getList()
  } catch {
  } finally {
    BtnLoading.value = false
  }
}

// 修改保存
const editSubmit = async () => {
  BtnLoading.value = true
  try {
    const valid = await ruleFormRef.value.validate()
    if (!valid) return
    const arr = ruleForm.docConfigCode

    // if (arr.audit.length < 1) return proxy.warningMsg('至少添加一条审核配置')
    // const auditIf = arr.audit.some(item => item.auditControl && item.auditTrigger && item.auditMalType)
    // if (!auditIf) return proxy.warningMsg('请填写一条完整的审核配置')

    // 送检配置开启时
    if (ruleForm.docInspectionMark == 1) {
      if (arr.check.length < 1) return proxy.warningMsg('至少添加一条检验配置')
      const checkIf = arr.check.some(item => item.checkSubmit && item.checkType && item.checkMode)
      if (!checkIf) return proxy.warningMsg('请填写一条完整的检验配置')
    }
    await EditDataAPI(ruleForm)
    proxy.successMsg('修改成功')
    close()
    getList()
  } catch {
  } finally {
    BtnLoading.value = false
  }
}

// 删除
const del = async val => {
  const MesBox = await proxy.DelMessageBox()
  // val.docId
  if (!MesBox) return
  // console.log(Ids.value.length)
  const res = await DelDataAPI(Ids.value.length <= 0 ? val : Ids.value.join(','))
  if (res.code !== 200) return
  proxy.successMsg('删除成功')
  getList()
}

// 弹窗结束
const close = () => {
  dialogVisible.value = false
  for (let KEY in ruleForm) {
    ruleForm[KEY] = ''
  }
  ruleForm.docConfigCode = {
    check: [],
    audit: []
  }
}

const docHandoverMarkChange = val => {
  if (val == 1) {
    rules.docHandoverMethod = [{ required: true, message: '请选择交换方式', trigger: 'change' }]
  } else {
    delete rules.docHandoverMethod
  }
}

// 选择单据
const nodeClick = async val => {
  ruleForm.docConfig = val[val.length - 1]
  getAnjian(val[val.length - 1])
}

// 查询案件下拉列表
const getAnjian = async id => {
  const res = await GetMenuPermsAPI(id)
  anjianList.value = res.data.map(item => ({
    label: item.menuName,
    value: item.menuId
  }))
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  const res = await GetListAPI(query)
  if (res.code !== 200) return
  total.value = res.total
  TableData.value = res.rows
  loading.value = false
}

// 查询按钮
const selectSubmit = val => {
  for (let KEY in val) {
    query[KEY] = val[KEY]
  }
  getList()
}

const transfer = ref()

const generateData = () => {
  const data = []
  const states = ['California', 'Illinois', 'Maryland', 'Texas', 'Florida', 'Colorado', 'Connecticut ']
  const initials = ['CA', 'IL', 'MD', 'TX', 'FL', 'CO', 'CT']
  states.forEach((city, index) => {
    data.push({
      label: city,
      key: index,
      initial: initials[index]
    })
  })
  return data
}

const data = ref(generateData())
const value = ref([])

const filterMethod = (query, item) => {
  return item.initial.toLowerCase().includes(query.toLowerCase())
}

/** 单据规则 查询列表 */
const billList = async () => {
  const res = await billListAPI({ pageNum: 1, pageSize: 999 })
  if (res.code !== 200) return
  docTheRulesOpt.value = res.rows.map(item => ({ label: item.ofCodeName, value: item.ofCodeStr }))
}

const menuOptions = ref([])

const getMenuPerm = async () => {
  const res = await GetMenuPermAPI()
  menuOptions.value = res.data
}

billList()
getList()
</script>
<template>
  <div class="app-container">
    <!-- 查询条件组件 -->
    <SelectForm :SelectForm="SelectList" @selectSubmit="selectSubmit" />
    <el-card class="box-card">
      <!-- 按钮组件 -->
      <el-button type="primary" v-hasPermi="['system:billconfig:add']" @click="add">添加单据</el-button>
      <el-button type="danger" v-hasPermi="['system:billconfig:remove']" :disabled="DelDisabled" @click="del"
        >批量删除</el-button
      >
      <!-- 表格数据 -->
      <el-table
        v-loading="loading"
        stripe
        border
        :data="TableData"
        style="margin-top: 20px"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" fixed="left" />
        <el-table-column label="序号" type="index" width="80"></el-table-column>
        <el-table-column label="配置编码" prop="docCode" width="220" />
        <el-table-column label="配置名称" prop="docName" width="120" />
        <el-table-column label="配置单据" prop="docConfigDict" width="180" />
        <el-table-column label="交接方式" prop="docHandoverMethodDict" width="180" />
        <el-table-column label="编码规则" prop="docTheRules" width="180" />
        <el-table-column label="超收标志" width="auto">
          <template #default="scope">
            <p-switch disabled v-model="scope.row.docExcessMark" />
          </template>
        </el-table-column>
        <el-table-column label="超发标志" width="auto">
          <template #default="scope">
            <p-switch disabled v-model="scope.row.docHairMark" />
          </template>
        </el-table-column>
        <el-table-column label="送检标志" width="auto">
          <template #default="scope">
            <p-switch disabled v-model="scope.row.docInspectionMark" />
          </template>
        </el-table-column>
        <el-table-column label="交接标志" width="auto">
          <template #default="scope">
            <p-switch disabled v-model="scope.row.docHandoverMark" />
          </template>
        </el-table-column>
        <el-table-column label="创建人" prop="createBy" width="150" />
        <el-table-column label="创建时间" prop="createTime" width="220" />
        <el-table-column label="操作" align="center" width="180" fixed="right">
          <template #default="scope">
            <div>
              <el-link type="primary" v-hasPermi="['system:billconfig:edit']" @click="edit(scope.row)">修改</el-link>
              <el-link type="primary" v-hasPermi="['system:billconfig:remove']" @click="del(scope.row.docId)"
                >删除</el-link
              >
              <el-link type="primary" v-hasPermi="['system:billconfig:query']" @click="look(scope.row)">查看</el-link>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="query.pageNum"
          v-model:limit="query.pageSize"
          @pagination="getList"
        />
      </div>
    </el-card>
    <!-- 新增弹窗 -->
    <p-XiaoheDialog :dialogVisible="dialogVisible" :title="title" @close="close">
      <template #body>
        <el-form ref="ruleFormRef" :inline="true" :model="ruleForm" :rules="rules" label-width="100px">
          <el-form-item label="配置编码" prop="docCode">
            <el-input clearable v-model="ruleForm.docCode" :disabled="title != '新增'" placeholder=" 请输入内容" />
          </el-form-item>
          <el-form-item label="配置名称" prop="docName">
            <el-input v-model="ruleForm.docName" :disabled="title == '查看'" clearable placeholder="请填写配置名称" />
          </el-form-item>
          <el-form-item label="配置单据" prop="docConfig">
            <el-cascader
              v-if="title == '新增'"
              v-model="ruleForm.docConfigs"
              :disabled="title == '查看'"
              :show-all-levels="false"
              :options="menuOptions"
              node-key="menuId"
              :props="{ label: 'menuName', value: 'menuId' }"
              @change="nodeClick"
            />
            <el-input v-else v-model="ruleForm.docConfigDict" disabled clearable placeholder="请填写配置名称" />
          </el-form-item>
          <el-form-item label="交接方式" prop="docHandoverMethod">
            <el-select
              :disabled="title == '查看'"
              v-model="ruleForm.docHandoverMethod"
              clearable
              placeholder="请选择交接方式"
            >
              <el-option
                v-for="(item, index) in sys_handover_method"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="编码规则" prop="docTheRules">
            <el-select
              :disabled="title == '查看'"
              filterable
              v-model="ruleForm.docTheRules"
              clearable
              placeholder="请选择编码规则"
            >
              <el-option
                v-for="(item, index) in docTheRulesOpt"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <div class="swBox">
          <div class="switch flex-items-center">
            <div class="flex-items-center">
              <label for="超收标志">超收标志</label>
              <p-switch :disabled="title == '查看'" v-model="ruleForm.docExcessMark" />
            </div>
            <div class="flex-items-center" style="margin-left: 20px">
              <label for="超收标志">交接标志</label>
              <p-switch
                @change="docHandoverMarkChange"
                :disabled="title == '查看'"
                v-model="ruleForm.docHandoverMark"
              />
            </div>
          </div>
          <div class="switch flex-items-center">
            <div class="flex-items-center">
              <label for="超收标志">超发标志</label>
              <p-switch :disabled="title == '查看'" v-model="ruleForm.docHairMark" />
            </div>
            <div class="flex-items-center" style="margin-left: 20px">
              <label for="超收标志">送检标志</label>
              <p-switch :disabled="title == '查看'" v-model="ruleForm.docInspectionMark" />
            </div>
          </div>
        </div>
        <!-- 表格表单 -->
        <el-card>
          <template #header>
            <div class="card-header">
              <el-tabs type="border-card" v-model="tabs">
                <!-- 检验配置 -->
                <el-tab-pane name="检验配置" label="检验配置">
                  <div class="caozuo" v-if="title == '新增' || title == '修改'">
                    <el-tooltip class="box-item" effect="dark" content="添加" placement="top-start">
                      <el-icon @click="addTypeFn"><Plus /></el-icon>
                    </el-tooltip>
                    <div style="margin: 0 10px"></div>
                    <el-tooltip class="box-item" effect="dark" content="勾选删除" placement="top-start">
                      <el-icon @click="removeTypeFn()"><Minus /></el-icon>
                    </el-tooltip>
                  </div>
                  <el-table
                    v-loading="loading"
                    stripe
                    border
                    :data="ruleForm.docConfigCode.check"
                    @selection-change="formTeblChange"
                  >
                    <el-table-column type="selection" width="55" align="center" />
                    <el-table-column label="序号" width="80">
                      <template #default="scope">{{ scope.$index + 1 }}</template>
                    </el-table-column>
                    <el-table-column label="送检阶别" width="auto">
                      <template #default="scope">
                        <el-select
                          :disabled="title == '查看'"
                          v-model="scope.row.checkSubmit"
                          clearable
                          placeholder="请选择"
                        >
                          <el-option
                            v-for="(item, index) in item_rank"
                            :key="index"
                            :label="item.label"
                            :value="item.value"
                          />
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="检验类型" width="auto">
                      <template #default="scope">
                        <el-select
                          :disabled="title == '查看'"
                          v-model="scope.row.checkType"
                          clearable
                          placeholder="请选择"
                        >
                          <el-option
                            v-for="(item, index) in sys_inspection_type"
                            :key="index"
                            :label="item.label"
                            :value="item.value"
                          />
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="送检方式" width="auto">
                      <template #default="scope">
                        <el-select
                          :disabled="title == '查看'"
                          v-model="scope.row.checkMode"
                          clearable
                          placeholder="请选择"
                        >
                          <el-option
                            v-for="(item, index) in sys_inspection_method"
                            :key="index"
                            :label="item.label"
                            :value="item.value"
                          />
                        </el-select>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-tab-pane>
                <!-- 审核配置 -->
                <!-- <el-tab-pane name="审核配置" label="审核配置">
                  <div class="caozuo" v-if="title == '新增' || title == '修改'">
                    <el-tooltip class="box-item" effect="dark" content="添加" placement="top-start">
                      <el-icon @click="addTypeFn"><Plus /></el-icon>
                    </el-tooltip>
                    <div style="margin: 0 10px"></div>
                    <el-tooltip class="box-item" effect="dark" content="勾选删除" placement="top-start">
                      <el-icon @click="removeTypeFn()"><Minus /></el-icon>
                    </el-tooltip>
                  </div>
                  <el-table
                    v-loading="loading"
                    stripe
                    border
                    :data="ruleForm.docConfigCode.audit"
                    @selection-change="examineFormTeblChange"
                  >
                    <el-table-column type="selection" width="55" align="center" />
                    <el-table-column label="序号" width="80">
                      <template #default="scope">{{ scope.$index + 1 }}</template>
                    </el-table-column>
                    <el-table-column label="管控项目" width="auto">
                      <template #default="scope">
                        <el-select
                          :disabled="title == '查看'"
                          v-model="scope.row.auditControl"
                          clearable
                          placeholder="请选择"
                        >
                          <el-option
                            v-for="(item, index) in sys_control_items"
                            :key="index"
                            :label="item.label"
                            :value="item.value"
                          />
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="触发按键" width="auto">
                      <template #default="scope">
                        <el-select
                          :disabled="title == '查看'"
                          v-model="scope.row.auditTrigger"
                          clearable
                          placeholder="请选择"
                        >
                          <el-option
                            v-for="(item, index) in anjianList"
                            :key="index"
                            :label="item.label"
                            :value="item.value"
                          />
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="物料类别" width="auto">
                      <template #default="scope">
                        <el-select
                          :disabled="title == '查看'"
                          v-model="scope.row.auditMalType"
                          clearable
                          placeholder="请选择"
                        >
                          <el-option
                            v-for="(item, index) in sys_material_category"
                            :key="index"
                            :label="item.label"
                            :value="item.value"
                          />
                        </el-select>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-tab-pane> -->
                <!-- PDA配置 -->
                <!-- <el-tab-pane label="PDA配置">
                  <el-transfer
                    v-model="transfer"
                    filterable
                    :titles="['未配置功能', '已配置功能']"
                    :filter-method="filterMethod"
                    filter-placeholder="请输入"
                    :data="data"
                  />
                </el-tab-pane> -->
              </el-tabs>
            </div>
          </template>
        </el-card>
        <!-- 按钮 -->
        <div class="Btn" v-if="title == '新增' || title == '修改'">
          <div style="flex: 1"></div>
          <el-button type="primary" :loading="BtnLoading" @click="title == '新增' ? addSubmit() : editSubmit()"
            >保存</el-button
          >
          <el-button @click="close">取消</el-button>
        </div>
      </template>
    </p-XiaoheDialog>
  </div>
</template>
<style scoped lang="scss">
.caozuo {
  float: right;
  display: flex;
  margin-bottom: 10px;
  justify-content: space-evenly;
}
.Btn {
  margin-top: 20px;
  display: flex;
  float: right;
}
.switch {
  display: flex;
}
.app-container v-deep .el-form-item__content {
  width: 228px;
}
.Xiaoheforms {
  display: flex;
}
.swBox {
  margin-left: 20px;
  .switch {
    display: flex;
    align-items: center;
    label {
      display: inline-block;
      width: 60px;
    }
  }
}
</style>
